package com.migu.contacts.net;

import com.blankj.utilcode.util.ToastUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class ResultCallback<T> implements Callback<Result<T>> {
    @Override
    public void onResponse(Call<Result<T>> call, Response<Result<T>> response) {
        if (response == null) {
            onError(500, "网络异常");
        } else {
            boolean successful = response.isSuccessful();
            if (successful) {
                Result<T> body = response.body();
                if (body == null) {
                    onError(100, "网络异常");
                } else {
                    int code = body.code;
                    if (code == 200) {
                        onSuccess(body.data);
                    } else {
                        onError(code, body.message);
                    }
                }
            } else {
                onError(response.code(), response.message());
            }
        }

    }

    protected abstract void onSuccess(T t);

    protected void onError(int code, String message) {
        ToastUtils.showShort(message);
    }

    @Override
    public void onFailure(Call<Result<T>> call, Throwable throwable) {
        onError(500, throwable.getMessage());
    }
}
